//
//  TEDownloadImage.m
//  ThaiExpress
//
//  Created by Le Quang Vinh on 7/16/13.
//  Copyright (c) 2013 Fruity. All rights reserved.
//

#import "TEDownloadImage.h"

@implementation TEDownloadImage

+ (void)downloadImage:(NSString *)urlImage
           WithFolder:(NSString *)folderPath
        WithImageName:(NSString *)imageName{
    NSString *imgURL = [NSString stringWithFormat:@"%@%@",kAPIBaseURKImage,urlImage];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        // Get dir
        NSString *documentsDirectory = nil;
        NSArray *paths      = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory  = [paths objectAtIndex:0];
        NSString *dataPath  = [documentsDirectory stringByAppendingPathComponent:folderPath];
        NSError *error;
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
        NSString *pathString = [NSString stringWithFormat:@"%@/%@",dataPath, imageName];
        
        // Save Image
        if ([[urlImage pathExtension] compare:@"png" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSString *pngFilePath = [NSString stringWithFormat:@"%@.png",pathString];
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
            [imageData writeToFile:pngFilePath atomically:YES];
        } else if ([[urlImage pathExtension] compare:@"jpg" options:NSCaseInsensitiveSearch] == NSOrderedSame ||
                   [[urlImage pathExtension] compare:@"jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSString *pngFilePath = [NSString stringWithFormat:@"%@.jpg",pathString];
            NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1)];
            [imageData writeToFile:pngFilePath atomically:YES];
        } else {
            DEBUGLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", @"extension");
        }
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        DEBUGLog(@"%@", [error localizedDescription]);
    }];
    [operation start];
}

@end